package com.obrempon.credit.market.ui.activity

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.View
import com.obrempon.credit.market.R
import com.obrempon.credit.market.configs.ObremponApiUrl
import com.obrempon.credit.market.configs.ObremponConfigs
import com.obrempon.credit.market.databinding.ObremponAuthStepsActBinding
import com.obrempon.credit.market.event.ObremponEventData
import com.obrempon.credit.market.event.ObremponEventPointType
import com.obrempon.credit.market.httptest.HttpAct
import com.obrempon.credit.market.request.IHttpCallback
import com.obrempon.credit.market.ui.fragment.ObremponAuthStepCommonFragment
import com.obrempon.credit.market.ui.fragment.ObremponAuthStepContactFragment
import com.obrempon.credit.market.ui.fragment.ObremponAuthStepOcrFragment
import com.obrempon.credit.market.ui.fragment.ObremponAuthStepSelfieFragment
import com.obrempon.credit.market.ui.fragment.ObremponAuthStepWalletAccountFragment
import com.obrempon.credit.market.utils.ObremponPickContactUtils
import com.obrempon.credit.market.utils.ObremponTitleBarUtil
import com.obrempon.credit.market.utils.helper.ObremponProcessHelper
import com.obrempon.module.shapeview.drawable.ShapeGradientOrientation
import org.json.JSONObject
import java.math.BigDecimal
import java.math.RoundingMode

/**
 * ObremponCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/18 18:51
 * @Annotation：进件流程
 */
open class ObremponAuthStepsAct: HttpAct(){
    lateinit var binding: ObremponAuthStepsActBinding

    private var eventStepTitle = ""
    //选择联系人
    var pickContact: ObremponPickContactUtils? = null

    companion object {
        private const val INTENT_KEY_AMOUNT = "amount"
        fun start(context: Context, amount: String) {
            val intent = Intent(context, ObremponAuthStepsAct::class.java)
            intent.putExtra(INTENT_KEY_AMOUNT, amount)
            context.startActivity(intent)
        }
    }

    override fun takeObremponRootView(): View? {
        binding = ObremponAuthStepsActBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initObremponView() {
        ObremponTitleBarUtil.setStatusBarLightMode(this, true)
        setObremponTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootLayout.shapeDrawableBuilder
            .setSolidGradientColors(getColor(R.color.color_ffcbe0ff),getColor(R.color.white),getColor(R.color.white))
            .setSolidGradientOrientation(ShapeGradientOrientation.TOP_TO_BOTTOM)
            .intoBackground()
        setObremponTextTitle(getString(R.string.obrempon_permission_title))
        setObremponTextTitle("")

        pickContact = ObremponPickContactUtils(this)
    }

    override fun initObremponListener() {
        rootViewBinding.rootCustomer.setOnClickListener {
            showCustomerDialog(eventStepTitle)
            addEventPointRequestAction(ObremponEventPointType.CLICK.OBREMPON_CLICK_CUSTOMER,eventStepTitle)
        }
    }

    override fun takeObremponData() {
        takeObremponAuthProgress()
        //上报 Battery 和 Wifi 信息
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_SYC_BATTERY_WIFI))
    }

    /**
     * 所有步骤已完成
     */
    private fun showObremponAuthStepCompleteViews() {
        onIntent(ObremponCreditReviewingAct::class.java)
        finish()
    }

    /**
     * 移除所有步骤
     */
    private fun removeObremponAuthStepAllViews() {
        binding.processCurrentLayout.removeAllViews()
    }

    /**
     * 设置认证步骤进度
     */
    @SuppressLint("SetTextI18n")
    fun showObremponAuthStepProgress(total: Int, progress: Int) {
        binding.authProgressBar.max = total
        binding.authProgressBar.progress = progress
        binding.textAuthCurrentProgress.text = BigDecimal("$progress").divide(BigDecimal("$total"),2, RoundingMode.UP).multiply(BigDecimal("100")).stripTrailingZeros().toPlainString()+"%"
        if (total != progress){
            binding.textAuthStepTitle.setTextColor(getColor(R.color.black))
        } else {
            binding.textAuthStepTitle.setTextColor(getColor(R.color.white))
        }
    }

    /**
     * 设置当前进行的步骤图标和名称
     */
    private fun showObremponAuthCurrentStep(icon: Int, title: String) {
        binding.imageAuthenticationStepIcon.setImageResource(icon)
        binding.textAuthStepTitle.text = title
    }

    /**
     * 联系人
     */
    private fun showObremponAuthStepContactView(data: JSONObject) {
        if (takeObremponIntentProductAmount().isNotEmpty()){
            //显示额度 = 额度 / 2
            val showAmount = BigDecimal(takeObremponIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
            data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        }
        replaceContainerFragement(R.id.processCurrentLayout, ObremponAuthStepContactFragment(this,data))
    }

    /**
     * 证件照Ocr
     */
    private fun showObremponAuthStepOcrView(data: JSONObject) {
        val showAmount = BigDecimal(takeObremponIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
        data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.1")).stripTrailingZeros().toPlainString())
        replaceContainerFragement(R.id.processCurrentLayout, ObremponAuthStepOcrFragment(data))
    }

    /**
     * 自拍照
     */
    private fun showObremponAuthStepSelfieView(data: JSONObject){
        replaceContainerFragement(R.id.processCurrentLayout, ObremponAuthStepSelfieFragment(data))
    }

    /**
     * 法语区 绑卡
     */
    private fun showObremponAuthStepBindWalletView(data: JSONObject) {
        replaceContainerFragement(R.id.processCurrentLayout, ObremponAuthStepWalletAccountFragment(data))
    }

    /**
     * 通用样式
     */
    private fun showObremponAuthStepCommonView(data: JSONObject) {
        if (takeObremponIntentProductAmount().isNotEmpty()){
            //显示额度 = 额度 / 2
            val showAmount = BigDecimal(takeObremponIntentProductAmount()).divide(BigDecimal("2"),2, RoundingMode.UP).stripTrailingZeros().toPlainString()
            data.put("creditLimitAmount",BigDecimal(showAmount).multiply(BigDecimal("0.05")).stripTrailingZeros().toPlainString())
        }
        replaceContainerFragement(R.id.processCurrentLayout, ObremponAuthStepCommonFragment(data))
    }

    /**
     * 提交
     */
    open fun onObremponAuthStepSubmitAction(params: JSONObject){
        onSubmitAuthStepAction(params)
    }

    /**
     * 流程提交成功
     * 需要发送通知刷新总流程
     */
    fun showObremponAuthStepSubmitSuccess() {
        //通知刷新总流程
        publishEventData(ObremponEventData(ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESH))
    }

    override fun onObremponPublishEvent(event: ObremponEventData) {
        super.onObremponPublishEvent(event)
        when(event.eventType){
            ObremponEventData.TYPE.OBREMPON_PROCESS_REFRESHED -> {
                takeObremponAuthProgress()
            }
            else -> {

            }
        }
    }

    /**
     * 获取产品额度
     */
    private fun takeObremponIntentProductAmount(): String{
        return intent.extras?.getString(INTENT_KEY_AMOUNT,"").toString()
    }

    /**
     * 加载流程步骤
     */
    private fun takeObremponAuthProgress(){
        removeObremponAuthStepAllViews()

        val allStepTitles = ObremponProcessHelper.takeObremponAuthAllStepTitleList()
        //当前进行的步骤
        val curtIndex = ObremponProcessHelper.takeObremponAuthStepIndex()
        val allSteps = ObremponProcessHelper.takeObremponAuthAllStepList()
        if (curtIndex == allSteps.size){//所有步骤已完成
            showObremponAuthStepCompleteViews()
            return
        }
        val showTitle = allStepTitles[curtIndex]
        showObremponAuthStepProgress(allSteps.size,curtIndex+1)
        showObremponAuthCurrentStep(takeStepIcon(allSteps[curtIndex]), showTitle)

        val processData = ObremponProcessHelper.takeObremponAuthData()
        eventStepTitle = allSteps[curtIndex]
        //是否是坦桑地区,需要根据语言显示
        if (ObremponConfigs.isObremponTanz()){
//            val stepTitleItem = JSONObject(stepTitle)
//            val curtLocale = Languages.getAppLanguage(iView.getAct())
//            stepTitle = when(curtLocale.language){
//                LocaleContract.getSwahiliLocale().language -> {//坦桑
//                    stepTitleItem.optString("sw")
//                }
//                else -> {
//                    stepTitleItem.optString("en")
//                }
//            }
        }
        //获取对应的key
        val curtKey = allSteps[curtIndex]
        //todo Contact 类型
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            stepData?.put("showTitle",showTitle)
            stepData?.put("stepTitle",eventStepTitle)
            if (stepData != null && stepData.has("isContact") && stepData.optString("isContact") == "YES"){
                showObremponAuthStepContactView(stepData)
                return
            }
        }

        //todo Ocr证件照样式
        if (curtKey.contains("ocr_info")){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showObremponAuthStepOcrView(stepData)
            return
        }

        //todo Selfie自拍照样式
        if (curtKey.contains("sefie_info")){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showObremponAuthStepSelfieView(stepData)
            return
        }

        //todo Account账户样式（法语地区绑定账号）
        if (curtKey.contains("account_info") && ObremponConfigs.isObremponFrench()){
            val stepData = JSONObject()
            stepData.put("showTitle",showTitle)
            stepData.put("stepTitle",eventStepTitle)
            showObremponAuthStepBindWalletView(stepData)
            return
        }
        //常规通用样式
        if (processData != null && processData.has(curtKey)){
            val stepData = processData.optJSONObject(curtKey)
            if (stepData != null) {
                stepData.put("showTitle",showTitle)
                stepData.put("stepTitle",eventStepTitle)
                showObremponAuthStepCommonView(stepData)
            }
        }
    }

    /**
     * 根据进件step名称获取对应的icon
     */
    private fun takeStepIcon(stepTitle: String): Int{
        when(stepTitle){
            "personal_info" -> {
                return R.mipmap.obrempon_auth_steps_personal_info_icon
            }
            "work_info" -> {
                return R.mipmap.obrempon_auth_steps_work_info_icon
            }
            "contact_info" -> {
                return R.mipmap.obrempon_auth_steps_contact_info_icon
            }
            "account_info" -> {
                return R.mipmap.obrempon_auth_steps_account_info_icon
            }
            "sefie_info" -> {
                return R.mipmap.obrempon_auth_steps_selfie_info_icon
            }
            "ocr_info" -> {
                return R.mipmap.obrempon_auth_steps_ocr_info_icon
            }
        }
        return R.mipmap.obrempon_auth_steps_personal_info_icon
    }


    /**
     * 提交数据
     */
    private fun onSubmitAuthStepAction(params: JSONObject){
        showObremponLoading()
        val httpUrl = ObremponApiUrl.queryEasyHttpUrl()
        doPostAction(httpUrl, params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                showObremponAuthStepSubmitSuccess()
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                hideObremponLoading()
            }
        })
    }

    override fun onStop() {
        super.onStop()
        binding.root.clearFocus()
    }
}